//
//  ST_RegisterResearchViewController.swift
//  btvideo
//
//  Created by mac on 2020/5/20.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import HandyJSON
import SwiftyUserDefaults



// 伴心小调查 暂时不用
// 2021-12-02 使用
class ST_RegisterResearchViewController: UIViewController, ST_RegisterRouteProtocol {


    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        //ST_BTGlobalDataCenter.shared.beginLogPageView("UserResearch")
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        //ST_BTGlobalDataCenter.shared.endLogPageView("UserResearch")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white

        view.addSubview(progress_view)
        progress_view.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(statusBarHeight + 25)
            make.height.equalTo(2)
        }
        
        view.addSubview(seekTitleLabel)
        seekTitleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(progress_view.snp.bottom).offset(26)
            make.height.equalTo(24)
        }
        
        view.addSubview(sub_title_label)
        sub_title_label.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(seekTitleLabel.snp.bottom).offset(4)
            make.height.equalTo(20)
        }

        view.addSubview(textFieldContainer)
        textFieldContainer.snp.makeConstraints { (make) in
            make.width.equalTo(300)
            make.height.equalTo(60)
            make.centerX.equalToSuperview()
            make.top.equalTo(sub_title_label.snp.bottom).offset(69)
        }

        textFieldContainer.addSubview(textField)
        textField.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 15))
        }


        view.addSubview(start_btn)

        start_btn.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-46)
            make.centerX.equalToSuperview()
            make.width.equalTo(260)
            make.height.equalTo(40)
        }

//        if let str = RegisterStepPersistence.filterSurvey()?.title{
//            seekTitleLabel.text = str
//        }

        //TianRegisterStepManager.shared.addHelperBtn(root_view: view)
    }


//    MARK: - Properties
    fileprivate lazy var progress_view: registerProgressView = {
        let v = registerProgressView()
//        v.setProgress(all: 6, p: 0)
        return v
    }()
    
    fileprivate lazy var seekTitleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "你从哪里看到我们并下载的？"
        control.textColor = Color.init(hexString: "#333333")
        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 17, weight: UIFont.Weight.medium)
        return control
    }()

    fileprivate lazy var sub_title_label: UILabel = {
        let l = UILabel()
        l.text = "这有助于我们改进推广，为你带来更多交友机会"
        l.textColor = Color.init(hexString: "#999999")
        l.textAlignment = .center
        l.font = .systemFont(ofSize: 14, weight: .regular)
        return l
    }()
    
    fileprivate lazy var textField:UITextField = {
       let control = UITextField()
        control.textColor = UIColor.init(hex: 0x333333)
        control.tintColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        control.textAlignment = .center
        
        let attrString = NSMutableAttributedString(string: "请手动输入")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 16),.foregroundColor: UIColor.init(hex: 0x999999) ?? .gray]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        control.attributedPlaceholder = attrString

        control.delegate = self
        return control
    }()

    fileprivate lazy var textFieldContainer:UIView = {
       let control = UIView()
        control.backgroundColor = Color.init(hex: 0xF2F2F2)
        control.cornerRadius = 30
        return control
    }()


    fileprivate lazy var start_btn:UIButton = {

        let control = UIButton.init(type: UIButton.ButtonType.custom)

        control.cornerRadius = 20


        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xFEC207)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.normal)

        control.setBackgroundImage(UIImage.init(color: UIColor.init(hex: 0xDFE3E9)!, size: CGSize.init(width: 1, height: 1)), for: UIControl.State.disabled)

        control.setTitleForAllStates("下一步")

        control.setTitleColorForAllStates(UIColor.white)

        control.setTitleColor(UIColor.white, for: UIControl.State.disabled)

        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)

        control.isEnabled = false

        control.addTarget(self, action: #selector(start_action), for: UIControl.Event.touchUpInside)

        return control
    }()

}


extension ST_RegisterResearchViewController:UITextFieldDelegate{

    @objc fileprivate func start_action(){

        self.show_indeterminate_h_u_d()

        let param = ["qudao": self.textField.text ?? ""] as [String : Any]

        JVrequest(PH.changeAvatarApi, parameters: param,success: { (json) in

            self.hidden_indeterminate_h_u_d()

//            TianRegisterStepManager.shared.pushNextStepAction()
            self.pushNextRegisterController(parameters: nil)
        }) { (code, err) in

            ToastHud(text: err, view: self.view)
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        guard var animal = textField.text else {
            return true
        }

        if let idxRange = Range.init(range, in: animal){

            animal.replaceSubrange(idxRange, with: string)

            start_btn.isEnabled = animal.count > 1

            return animal.count <= 24

        }else{
            return true
        }


    }
}

class registerProgressView: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .clear
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 修改为内部子视图的约束 来  约定外部的 width,  So  外部不用在设置 width
    func setProgress(currentIndex:Int,amount:Int,itemWidth:CGFloat = 53,gap:CGFloat = 4) {
        
        self.removeSubviews()
      
        var last: UIView?
        for index in 0 ..< amount {
            
            let safeView: UIView
            if currentIndex >= index {
                safeView = creatView(isOver: true)
            }else {
                safeView = creatView(isOver: false)
            }
            
            self.addSubview(safeView)
            safeView.snp.makeConstraints { make in
                if let safeLast = last {
                    make.left.equalTo(safeLast.snp.right).offset(gap)
                }else{
                    make.left.equalToSuperview()
                }
                make.width.equalTo(itemWidth)
                make.top.bottom.equalToSuperview()
                /// 最后一个
                if index + 1 == amount{
                    make.right.equalToSuperview()
                }
            }
            last = safeView
        }
    }
    
    private func creatView(isOver: Bool) -> UIView {
        let v = UIView()
        v.backgroundColor = isOver ? UIColor.init(hex: 0xFEC207) : UIColor.init(hex: 0xF2F2F2)
        v.cornerRadius = 1
        return v
    }
}
